package com.css.zfzx.fxpg.modules.buildings.census.repository.impl;

import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.role.repository.entity.RoleEntity;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.zfzx.fxpg.common.utils.ServerUtil;
import com.css.zfzx.fxpg.common.utils.cluster.Bounds;
import com.css.zfzx.fxpg.common.utils.cluster.Point;
import com.css.zfzx.fxpg.modules.buildings.census.repository.FxCountryJhHouseNativeRepository;
import com.css.zfzx.fxpg.modules.buildings.census.repository.entity.FxCountryJhHouseEntity;
import com.css.zfzx.fxpg.modules.buildings.census.viewobjects.FxHouseQueryParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author andy
 * @date 2020-11-11
 */
@Repository
@PropertySource("classpath:platform-config.yml")
public class FxCountryJhHouseNativeRepositoryImpl implements FxCountryJhHouseNativeRepository {
    @PersistenceContext
    private EntityManager em;

    @Value("${role.superCode}")
    private String superCode;
    @Value("${role.provinceCode}")
    private String provinceCode;
    @Value("${role.cityCode}")
    private String cityCode;
    @Value("${role.areaCode}")
    private String areaCode;

    private static final Logger log = LoggerFactory.getLogger(FxCountryJhHouseNativeRepositoryImpl.class);

    @Override
    public Page<FxCountryJhHouseEntity> queryFxCountryJhHouses(FxHouseQueryParams queryParams, int curPage, int pageSize, String sort, String order, String userId) {
        StringBuilder sql = new StringBuilder("select * from risk_census_country_jh_house ");
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");
        if(!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            whereSql.append(" and province like :province");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            whereSql.append(" and city like :city");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            whereSql.append(" and district like :district");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getYear())) {
            whereSql.append(" and build_time like :build_time");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getBuildingName())) {
            whereSql.append(" and jzmc like :jzmc");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getStructureType())) {
            whereSql.append(" and jglx = :jglx");
        }
        if (!PlatformObjectUtils.isEmpty(sort)) {
            whereSql.append(" order by " + sort + " " + order);
        }
        userId = (userId != null ? userId : PlatformSessionUtils.getUserId());
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        // 是否为超级管理员
        boolean containtRole = ServerUtil.isContaintRole(roles, superCode);
        // 是否为省级管理员
        boolean containtRolePro = ServerUtil.isContaintRole(roles, provinceCode);
        // 是否为市级管理员
        boolean containtRoleCity = ServerUtil.isContaintRole(roles, cityCode);
        // 是否为区级管理员
        boolean containtRoleArea = ServerUtil.isContaintRole(roles, areaCode);

        if (!containtRole) {
            // 如果都不是只能查看个人表单
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                whereSql.append(" and create_user =:user");
            }
            // 省级管理员
            if (containtRolePro) {
                whereSql.append(" and province like :divisionCode");
            }
            // 市级管理员
            if (containtRoleCity) {
                whereSql.append(" and city like :divisionCode");
            }
            // 区级管理员
            if (containtRoleArea) {
                whereSql.append(" and district like :divisionCode");
            }
        }
        Query query = this.em.createNativeQuery(sql.append(whereSql).toString(), FxCountryJhHouseEntity.class);
        StringBuilder countSql = new StringBuilder("select count(*) from risk_census_country_jh_house ");
        Query countQuery = this.em.createNativeQuery(countSql.append(whereSql).toString());
        if(!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            query.setParameter("province", "%" + queryParams.getProvince() + "%");
            countQuery.setParameter("province", "%" + queryParams.getProvince() + "%");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            query.setParameter("city", "%" + queryParams.getCity() + "%");
            countQuery.setParameter("city", "%" + queryParams.getCity() + "%");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            query.setParameter("district", "%" + queryParams.getArea() + "%");
            countQuery.setParameter("district", "%" + queryParams.getArea() + "%");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getYear())) {
            query.setParameter("build_time", "%" + queryParams.getYear() + "%");
            countQuery.setParameter("build_time", "%" + queryParams.getYear() + "%");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getBuildingName())) {
            query.setParameter("jzmc", "%" + queryParams.getBuildingName() + "%");
            countQuery.setParameter("jzmc", "%" + queryParams.getBuildingName() + "%");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getStructureType())) {
            query.setParameter("jglx", queryParams.getStructureType());
            countQuery.setParameter("jglx", queryParams.getStructureType());
        }
        if (!containtRole) {
            // 如果都不是只能查看个人表单
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                // 根据用户id查询
                query.setParameter("user", userId);
                countQuery.setParameter("user", userId);
            }
            // 省级管理员 市级管理员 区级管理员
            if (containtRolePro || containtRoleCity || containtRoleArea) {
                // 获取部门地区名称
                String divisionCode = ServerUtil.getDivisionEntity(userId).getDivisionCode();
                query.setParameter("divisionCode", "%" + divisionCode + "%");
                countQuery.setParameter("divisionCode", "%" + divisionCode + "%");
            }
        }
        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        query.setMaxResults(pageable.getPageSize());
        List<FxCountryJhHouseEntity> list = query.getResultList();
        BigInteger count = (BigInteger) countQuery.getSingleResult();
        Page<FxCountryJhHouseEntity> fxBuildingsPage = new PageImpl<>(list, pageable, count.longValue());
        return fxBuildingsPage;
    }

    @Override
    public List<FxCountryJhHouseEntity> listFxCountryJhHouses(FxHouseQueryParams queryParams, String userId) {
        StringBuilder sql = new StringBuilder("select * from risk_census_country_jh_house ");
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");
        if (!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            whereSql.append(" and province like :province");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            whereSql.append(" and city like :city");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            whereSql.append(" and district like :district");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYear())) {
            whereSql.append(" and build_time like :build_time");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getBuildingName())) {
            whereSql.append(" and jzmc like :jzmc");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getStructureType())) {
            whereSql.append(" and jglx = :jglx");
        }
        userId = (userId != null ? userId : PlatformSessionUtils.getUserId());
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        // 是否为超级管理员
        boolean containtRole = ServerUtil.isContaintRole(roles, superCode);
        // 是否为省级管理员
        boolean containtRolePro = ServerUtil.isContaintRole(roles, provinceCode);
        // 是否为市级管理员
        boolean containtRoleCity = ServerUtil.isContaintRole(roles, cityCode);
        // 是否为区级管理员
        boolean containtRoleArea = ServerUtil.isContaintRole(roles, areaCode);

        if (!containtRole) {
            // 如果都不是只能查看个人表单
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                whereSql.append(" and create_user =:user");
            }
            // 省级管理员
            if (containtRolePro) {
                whereSql.append(" and province like :divisionCode");
            }
            // 市级管理员
            if (containtRoleCity) {
                whereSql.append(" and city like :divisionCode");
            }
            // 区级管理员
            if (containtRoleArea) {
                whereSql.append(" and district like :divisionCode");
            }
        }
        Query query = this.em.createNativeQuery(sql.append(whereSql).toString(), FxCountryJhHouseEntity.class);
        if (!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            query.setParameter("province", "%" + queryParams.getProvince() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            query.setParameter("city", "%" + queryParams.getCity() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            query.setParameter("district", "%" + queryParams.getArea() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYear())) {
            query.setParameter("build_time", "%" + queryParams.getYear() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getBuildingName())) {
            query.setParameter("jzmc", "%" + queryParams.getBuildingName() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getStructureType())) {
            query.setParameter("jglx", queryParams.getStructureType());
        }
        if (!containtRole) {
            // 如果都不是只能查看个人表单
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                // 根据用户id查询
                query.setParameter("user", userId);
            }
            // 省级管理员 市级管理员 区级管理员
            if (containtRolePro || containtRoleCity || containtRoleArea) {
                // 获取部门地区名称
                String divisionCode = ServerUtil.getDivisionEntity(userId).getDivisionCode();
                query.setParameter("divisionCode", "%" + divisionCode + "%");
            }
        }
        List<FxCountryJhHouseEntity> list = query.getResultList();
        return list;
    }

    @Override
    public List<FxCountryJhHouseEntity> searchFxCountryJhHouses(FxHouseQueryParams queryParams, String userId) {
        StringBuilder sql = new StringBuilder("select * from risk_census_country_jh_house ");
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");
        if (!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            whereSql.append(" and province like :province");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            whereSql.append(" and city like :city");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            whereSql.append(" and district like :district");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYear())) {
            whereSql.append(" and build_time = :build_time");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getBuildingName())) {
            whereSql.append(" and jzmc like :jzmc");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getStructureType())) {
            whereSql.append(" and jglx = :jglx");
        }

        /*Bounds bounds = null;
        if (!PlatformObjectUtils.isEmpty(queryParams.getBounds())) {
            String coordinate = queryParams.getBounds();
            String[] coords = coordinate.split(",");
            String[] coord0 = coords[0].split(" ");
            String[] coord1 = coords[1].split(" ");
            bounds = new Bounds(new Point(Float.parseFloat(coord0[0]), Float.parseFloat(coord0[1])), new Point(Float.parseFloat(coord1[0]), Float.parseFloat(coord1[1])));
            //whereSql.append(" and MBRContains(ST_GeometryFromText('POLYGON ((" + coords[0] + "," + (coord0[0] + " " + coord1[1]) + "," + coords[1] + "," + (coord1[0] + " " + coord0[1]) + "," + coords[0] + "))'), geo_point)");
        }*/
        userId = (userId != null ? userId : PlatformSessionUtils.getUserId());
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        // 是否为超级管理员
        boolean containtRole = ServerUtil.isContaintRole(roles, superCode);
        // 是否为省级管理员
        boolean containtRolePro = ServerUtil.isContaintRole(roles, provinceCode);
        // 是否为市级管理员
        boolean containtRoleCity = ServerUtil.isContaintRole(roles, cityCode);
        // 是否为区级管理员
        boolean containtRoleArea = ServerUtil.isContaintRole(roles, areaCode);

        if (!containtRole) {
            // 如果都不是只能查看个人表单
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                whereSql.append(" and create_user =:user");
            }
            // 省级管理员
            if (containtRolePro) {
                whereSql.append(" and province like :divisionCode");
            }
            // 市级管理员
            if (containtRoleCity) {
                whereSql.append(" and city like :divisionCode");
            }
            // 区级管理员
            if (containtRoleArea) {
                whereSql.append(" and district like :divisionCode");
            }
        }


        Query query = this.em.createNativeQuery(sql.append(whereSql).toString(), FxCountryJhHouseEntity.class);
        if (!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            query.setParameter("province", "%" + queryParams.getProvince() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            query.setParameter("city", "%" + queryParams.getCity() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            query.setParameter("district", "%" + queryParams.getArea() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getYear())) {
            query.setParameter("build_time", "%" + queryParams.getYear() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getBuildingName())) {
            query.setParameter("jzmc", "%" + queryParams.getBuildingName() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getStructureType())) {
            query.setParameter("jglx", queryParams.getStructureType());
        }
        if (!containtRole) {
            // 如果都不是只能查看个人表单
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                // 根据用户id查询
                query.setParameter("user", userId);
            }
            // 省级管理员 市级管理员 区级管理员
            if (containtRolePro || containtRoleCity || containtRoleArea) {
                // 获取部门地区名称
                String divisionCode = ServerUtil.getDivisionEntity(userId).getDivisionCode();
                query.setParameter("divisionCode", "%" + divisionCode + "%");
            }
        }
        List<FxCountryJhHouseEntity> list = query.getResultList();
        return list;
    }

}
